package com.chenbei.controller.admin.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chenbei.common.annotation.OperationLog;
import com.chenbei.common.util.ApiResponseUtil;
import com.chenbei.common.util.PaginationUtil;
import com.chenbei.common.domain.vo.ApiResponse;
import com.chenbei.common.domain.vo.Pagination;
import com.chenbei.system.domain.SysConfig;
import com.chenbei.system.service.ISysConfigService;
import com.chenbei.system.vo.req.SysConfigReq;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "配置管理")
@RestController
@RequestMapping("/admin/system/config")
public class ConfigController {

    @Autowired
    private ISysConfigService configService;

    @SaCheckPermission(value = "system:config:add", orRole = "root")
    @PostMapping("add")
    @Operation(summary = "新增配置")
    @OperationLog(moduleName = "配置管理", eventName = "新增配置")
    public ApiResponse<Object> add(@Valid @RequestBody SysConfig config) {
        configService.add(config);

        return ApiResponseUtil.success();
    }

    @SaCheckPermission(value = "system:config:delete", orRole = "root")
    @PostMapping("deleteById/{id}")
    @Operation(summary = "删除配置")
    @OperationLog(moduleName = "配置管理", eventName = "删除配置")
    public ApiResponse<Object> delete(@PathVariable Long id) {
        configService.deleteById(id);

        return ApiResponseUtil.success();
    }

    @SaCheckPermission(value = "system:config:update", orRole = "root")
    @PostMapping("update")
    @Operation(summary = "更新配置")
    @OperationLog(moduleName = "配置管理", eventName = "更新配置")
    public ApiResponse<Object> update(@Valid @RequestBody SysConfig config) {
        configService.update(config);

        return ApiResponseUtil.success();
    }

    @SaCheckPermission(value = "system:config:list", orRole = "root")
    @GetMapping("listPage")
    @Operation(summary = "分页列表")
    public ApiResponse<Pagination<SysConfig>> listPage(SysConfigReq sysConfigReq) {
        Page<SysConfig> configEntityPage = configService.listPage(sysConfigReq);
        return ApiResponseUtil.success(PaginationUtil.toPagination(configEntityPage));
    }

    @SaCheckPermission(value = "system:config:get", orRole = "root")
    @GetMapping("getByKey")
    @Operation(summary = "通过键名获取配置信息")
    @Parameters( {
            @Parameter(name = "key", description = "键名")
    })
    public ApiResponse<SysConfig> getByKey(@RequestParam String key) {
        SysConfig config = configService.getByKey(key);

        return ApiResponseUtil.success(config);
    }
}
